package com.mlan.userap.untils;
import android.content.Context;
import android.net.Uri;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.BufferedSink;
import okio.Okio;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

public class FileUploader {

    // 定义进度监听接口
    public interface UploadProgressListener {
        void onProgress(long bytesUploaded, long totalBytes);

        void onResponse(Response response);
        void onFailure(IOException e);
    }





    // 单例实例
    private static volatile FileUploader instance;

    // OkHttpClient 实例
    private final OkHttpClient client;

    // 私有构造方法，防止外部直接实例化
    private FileUploader() {
        client = new OkHttpClient.Builder()
                .connectTimeout(60, java.util.concurrent.TimeUnit.SECONDS)
                .writeTimeout(60, java.util.concurrent.TimeUnit.SECONDS)
                .readTimeout(60, java.util.concurrent.TimeUnit.SECONDS)
                .build(); // 可以在这里配置 OkHttpClient，例如超时时间等
    }

    // 获取单例实例的公共方法
    public static FileUploader getInstance() {
        if (instance == null) {
            synchronized (FileUploader.class) {
                if (instance == null) {
                    instance = new FileUploader();
                }
            }
        }
        return instance;
    }

    // 异步上传文件（File）
    public void uploadFileAsync(String url, File file, UploadProgressListener listener) {
        RequestBody requestBody = new RequestBody() {
            @Override
            public MediaType contentType() {
                return MediaType.parse("application/octet-stream");
            }

            @Override
            public long contentLength() {
                return file.length();
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                try (okio.Source source = Okio.source(file)) {

                    long totalBytes = contentLength();
                    long bytesUploaded = 0;

                    okio.Buffer buffer = new okio.Buffer();
                    long bytesRead;

                    while ((bytesRead = source.read(buffer, 8192)) != -1) {
                        // 从 buffer 中读取指定数量的字节到 byteArray
                        byte[] byteArray = buffer.readByteArray(bytesRead);
                        sink.write(byteArray, 0, (int) bytesRead);
                        bytesUploaded += bytesRead;
                        if (listener != null) {
                            long finalBytesUploaded = bytesUploaded;
                            new android.os.Handler(android.os.Looper.getMainLooper()).post(() -> {
                                listener.onProgress(finalBytesUploaded, totalBytes);
                            });
                        }
                    }

                }
            }
        };

        Request request = new Request.Builder()
                .url(url)
                .put(requestBody)

                .build();

        client.newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
                e.printStackTrace();
                if (listener != null) {
                    listener.onFailure(e);
                }
                System.out.println("上传失败: " + e.getMessage());
            }

            @Override
            public void onResponse(okhttp3.Call call, Response response) throws IOException {
                if (listener != null) {
                    listener.onResponse(response);
                }
                if (response.isSuccessful()) {
                    System.out.println("上传成功: " + response.body().string());
                } else {
                    System.out.println("上传失败: " + response.code());
                }
            }
        });
    }

    // 异步上传文件（Uri）
    public void uploadFileFromUriAsync(Context context, String url, Uri uri, UploadProgressListener listener) {
        try {
            InputStream inputStream = context.getContentResolver().openInputStream(uri);
            if (inputStream == null) return;

            RequestBody requestBody = new RequestBody() {
                @Override
                public MediaType contentType() {
                    return MediaType.parse("application/octet-stream");
                }

                @Override
                public long contentLength() throws IOException {
                    return inputStream.available();
                }

                @Override
                public void writeTo(BufferedSink sink) throws IOException {
                    long totalBytes = contentLength();
                    long bytesUploaded = 0;

                    byte[] buffer = new byte[8192];
                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        sink.write(buffer, 0, bytesRead);
                        bytesUploaded += bytesRead;
                        if (listener != null) {
                            long finalBytesUploaded = bytesUploaded;
                            new android.os.Handler(android.os.Looper.getMainLooper()).post(() -> {
                                listener.onProgress(finalBytesUploaded, totalBytes);
                            });

                        }
                    }
                    inputStream.close();
                }
            };

            Request request = new Request.Builder()
                    .url(url)
                    .put(requestBody)
                    .build();

            client.newCall(request).enqueue(new okhttp3.Callback() {
                @Override
                public void onFailure(okhttp3.Call call, IOException e) {
                    if (listener != null) {
                        listener.onFailure(e);
                    }
                    e.printStackTrace();
                    System.out.println("上传失败: " + e.getMessage());
                }

                @Override
                public void onResponse(okhttp3.Call call, Response response) throws IOException {
                    if (listener != null) {
                        listener.onResponse(response);
                    }
                    if (response.isSuccessful()) {
                        System.out.println("上传成功: " + response.body().string());
                    } else {
                        System.out.println("上传失败: " + response.code());
                    }
                }
            });

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void uploadFileAAC(String url, File file,long time, UploadProgressListener listener) {
        RequestBody requestBody = new RequestBody() {
            @Override
            public MediaType contentType() {
                return MediaType.parse("application/octet-stream");
            }

            @Override
            public long contentLength() {
                return file.length();
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                try (okio.Source source = Okio.source(file)) {

                    long totalBytes = contentLength();
                    long bytesUploaded = 0;

                    okio.Buffer buffer = new okio.Buffer();
                    long bytesRead;

                    while ((bytesRead = source.read(buffer, 8192)) != -1) {
                        // 从 buffer 中读取指定数量的字节到 byteArray
                        byte[] byteArray = buffer.readByteArray(bytesRead);
                        sink.write(byteArray, 0, (int) bytesRead);
                        bytesUploaded += bytesRead;
                        if (listener != null) {
                            long finalBytesUploaded = bytesUploaded;
                            new android.os.Handler(android.os.Looper.getMainLooper()).post(() -> {
                                listener.onProgress(finalBytesUploaded, totalBytes);
                            });
                        }
                    }

                }
            }
        };

        Request request = new Request.Builder()
                .url(url)
                .put(requestBody)

                .build();

        client.newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
                e.printStackTrace();
                if (listener != null) {
                    listener.onFailure(e);
                }
                System.out.println("上传失败: " + e.getMessage());
            }

            @Override
            public void onResponse(okhttp3.Call call, Response response) throws IOException {
                if (listener != null) {
                    listener.onResponse(response);
                }
                if (response.isSuccessful()) {
                    System.out.println("上传成功: " + response.body().string());
                } else {
                    System.out.println("上传失败: " + response.code());
                }
            }
        });
    }
}